﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class UserControl_UpFileAction : System.Web.UI.Page
{
    private static string newFileName = "";
    private static string newFileSize = "";
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            SaveFileToTmp();
            Response.Write(newFileName + "|" + newFileSize);
        }
        catch
        {
            // If any kind of error occurs return a 500 Internal Server error
            Response.StatusCode = 500;
            Response.Write("An error occured");
            Response.End();
        }
    }

    /// <summary>
    /// 临时存储文件在服务器目录
    /// </summary>
    private void SaveFileToTmp()
    {
        System.Web.HttpFileCollection files = System.Web.HttpContext.Current.Request.Files;
        int fileCount;
        int filecount = files.Count;
        try
        {
            for (fileCount = 0; fileCount < files.Count; fileCount++)
            {
                //定义访问客户端上传文件的对象
                System.Web.HttpPostedFile postedFile = files[fileCount];

                string FileType = postedFile.ContentType.ToString();//获取要上传的文件类型,验证文件头  

                string fileName, fileExtension, fileRealName;
                //取得上传得文件名
                fileName = System.IO.Path.GetFileName(postedFile.FileName);
                //取得文件的扩展名
                fileExtension = System.IO.Path.GetExtension(fileName);
                //取得真实文件名




                fileRealName = System.IO.Path.GetFileName(fileName);
                string name = CommonLib.ComMon.StringCommon.StringEncode(fileRealName);


                //不限类型，只限10M大小
                if (postedFile.ContentLength / 1024 <= 30720000)
                {
                    if (fileName != String.Empty)
                    {  //+ Server.MapPath("../TmpFile/")
                        fileName = RandomFileName() + fileExtension;
                        //保存到指定的文件夹

                        postedFile.SaveAs(Server.MapPath("../TmpFile/") + fileName);
                        newFileName = fileName;
                        fileName = "";
                        newFileSize = postedFile.ContentLength.ToString();
                    }
                }
            }
        }
        catch (Exception)
        {

        }
    }
    private string RandomFileName()
    {//返回随机数的类

        string filename = "";
        string r1 = "";
        string r2 = "";
        string r4 = "";
        Random random = new Random();
        r1 = ((char)random.Next(65, 90)).ToString();//大写字母
        r2 = ((char)random.Next(97, 122)).ToString();//小写字母        
        r4 = random.Next(1000, 9999).ToString();

        filename = DateTime.Now.ToString("yyyyMMddHHmmss") + r4;
        return filename;

    }
}
